import sys
parent_dir = "../pygl"
sys.path.append(parent_dir)
import ctypes
import OpenGL.GL as gl
import glm
import imgui
import glfw
from glfw import _GLFWwindow as GLFWwindow
import numpy as np
import pygl
from common import AppWithTrackball, Cube, AxesHelper, GridHelper

class GridApp(AppWithTrackball):
    # 初始化着色器，vao vbo等
    def setupVertex(self) -> None:
        gl.glEnable(gl.GL_DEPTH_TEST)
        self.background_color = glm.vec4(0.3, 0.3, 0.3, 1.0)
        self.cube = Cube(tex_file="textures/cratetex.png")
        self.cube_axes = AxesHelper(0.4, 5.0)
        self.world_axes = AxesHelper(0.9, 2.0)
        self.grid = GridHelper(4.0, 20, glm.vec3(1.0, 1.0, 0.0))
        self.imgui_window_width = 250
        self.imgui_window_height = 300
        self.show_world_axes = True
        self.show_grid = True

    # 配置imgui界面元素
    def showImGui(self)->None:
        imgui.begin("设置")
        imgui.text("按住鼠标左键拖动旋转物体。")
        imgui.text("滚动鼠标滚轮可以缩放物体。")
        imgui.text("向前滚动是放大；\n向后滚动是缩小。")
        imgui.text("按住鼠标右键拖动移动物体")
        if imgui.button("重置"):
            self.camera.reset(glm.vec3(0.0, 0.0, 3.0), glm.vec3(0.0, 0.0, 0.0), 
                    glm.vec3(0.0, 1.0, 0.0))
        _, self.cube.use_vertex_color = imgui.checkbox("使用顶点颜色", 
                                                self.cube.use_vertex_color)
        _, self.show_world_axes = imgui.checkbox("显示三维世界坐标轴", 
                                                self.show_world_axes)
        _, self.show_grid = imgui.checkbox("显示XZ平面网格", 
                                                self.show_grid)
        imgui.end()       

    # 渲染图形
    def render(self) -> None:
        gl.glClearBufferfv(gl.GL_COLOR, 0, self.background_color.to_tuple())
        gl.glClearBufferfv(gl.GL_DEPTH, 0, 1.0)
        self.view = self.camera.getViewMatrix()
        self.projection = self.camera.getProjectionMatrix()
        self.cube.updateModelMatrix()
        self.cube.render(self.view,self.projection)
        self.cube_axes.model_matrix = self.cube.model_matrix
        self.cube_axes.render(self.view, self.projection)
        if self.show_world_axes:
            self.world_axes.updateModelMatrix()
            self.world_axes.render(self.view, self.projection)
        if self.show_grid:
            self.grid.render(self.view, self.projection)

    # 释放资源
    def cleanup(self) -> None:
        self.cube.delete()
        self.cube_axes.delete()
        self.world_axes.delete()
        self.grid.delete()

if __name__ == "__main__":
    app = GridApp(100, 100, 800, 800, "你好，网格App！")
    app.run()

